package coreEvent

import (
	"encoding/json"
	"log"
	"path"
	"time"

	"github.com/parnurzeal/gorequest"
	"smartconn.cc/tosone/parsing/parsing"
	"smartconn.cc/tosone/ra_main/PFSE"
	"smartconn.cc/tosone/ra_main/common"
	"smartconn.cc/tosone/ra_main/config"
	"smartconn.cc/tosone/ra_main/ledutil"
	"smartconn.cc/tosone/ra_main/store"
)

// Pagevt 翻页事件
func Pagevt(feature string) {
	if getStatus("bookStatus") == "false" {
		return
	}

	currMode := store.GetCurrMode()
	currRole := store.GetCurrRole()

	// search in searchengine
	var id string // BookID or PageID

	id = PFSE.Search(feature)
	count := 0
	for id == "" && count < config.MaxRepeatSearch { // 重复的寻找这本书
		if getStatus("bookStatus") != "true" {
			log.Println("No book on. Please check your book is still here.")
			return
		}
		count = count + 1
		feature = PFSE.GetFeature()
		time.Sleep(time.Millisecond * 50)
		id = PFSE.Search(feature)
		if id != "" {
			break
		}
	}
	if getStatus("bookStatus") != "true" {
		log.Println("No book on. Please check your book is still here.")
		return
	}
	if id == "" {
		log.Println("SearchEngine cannot find this book. Post the feature to server.")
		request := gorequest.New().Timeout(3 * time.Second)
		params := searchRequestParams{Feature: PFSE.GetFeature()}
		log.Println(config.BaseURL + "/api/devices/E0:B9:4D:31:69:12/book-search")
		resp, body, errs := request.Post(config.BaseURL + "/api/devices/E0:B9:4D:31:69:12/book-search").Send(params).End()

		if resp.StatusCode == 200 && len(errs) == 0 {
			log.Println(body)
			var res searchRespParams
			err = json.Unmarshal([]byte(body), &res)
			if err != nil {
				log.Println(err)
				return
			}
			// 添加下载任务
			task := common.TaskContentDownload{File: res.File, Uncompress: false}
			downloadTask, err := json.Marshal(task)
			if err != nil {
				log.Println(err)
				return
			}
			store.AddTask("download", string(downloadTask))
		} else {
			log.Println("Server response code:", resp.StatusCode, errs)
		}

		lastPageInfo = map[string]interface{}{}
		ledutil.Red()
		return
	}
	if getStatus("currBook") == "" {
		setStatus("currBook", id)
		slaveDB, err = store.OpenStory(path.Join(config.StoryDir, id))
		if err != nil {
			log.Println(err)
			return
		}
		log.Println(path.Join(config.StoryDir, id))
		// push pages to searchengine
		log.Println("Add features to searchengine.")
		for _, page := range slaveDB.GetPages() {
			PFSE.AddFeature(page)
		}
		log.Println("Success add features to searchengine.")
	}

	if getStatus("currPage") == id { // 没有翻页
		log.Println("The same page. Nothing to change.")
		return
	}

	setStatus("currPage", id)

	log.Println("Success get a new valid page.")

	currPageInfo := slaveDB.GetPage(id, currRole)
	defaultPageInfo := slaveDB.GetPage(id, "default")

	var pageInfo map[string]interface{}

	if currMode == "" || currMode == "default" {
		if len(defaultPageInfo) != 0 {
			pageInfo = defaultPageInfo
		} else {
			pageInfo = currPageInfo
		}
	} else if currMode == "user" {
		if len(currPageInfo) != 0 {
			pageInfo = currPageInfo
		} else {
			pageInfo = defaultPageInfo
		}
	} else if currMode == "mix" {
		if len(defaultPageInfo) != 0 {
			pageInfo = defaultPageInfo
		} else {
			pageInfo = currPageInfo
		}
	}

	parsing.Stop() // 停止 parsing

	ShortPushHome(false) // 完成上一页的录音

	ledutil.Close() // 停止 LED

	if len(pageInfo) != 0 {
		lastPageInfo = pageInfo
		go parsing.Start(path.Join(config.StoryDir, getStatus("currBook"), pageInfo["role"].(string)), pageInfo["manifest"].(string))
	} else {
		log.Println("RA database cannot find anything for this page.")
	}
}

// RestorePage 上一页重新唤起
func RestorePage() {
	parsing.Stop()
	if getStatus("bookStatus") == "true" && len(lastPageInfo) != 0 {
		go parsing.Start(path.Join(config.StoryDir, getStatus("currBook"), lastPageInfo["role"].(string)), lastPageInfo["manifest"].(string))
	} else {
		log.Println("Cannot restore last page.")
	}
}
